﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using Cloud.Core.Model;
using Cloud.Core.Response;
using Cloud.Core.AuthUser;
using Microsoft.EntityFrameworkCore.Internal;
using Cloud.Core.Bizlogic;
using Cloud.Core.ModelSearch;
using System.Threading;

namespace Cloud.Core.Controllers
{
    /// <summary>
    /// 业务逻辑
    /// </summary> 
    [Route("api/v1/[controller]")]
    [ApiController]
    public class AppleController : ControllerBase
    {
        private readonly CloudDataBase _context;
        private readonly ModOperate.Mod _thisModel = ModOperate.Mod.MBasicInfo;
        public AppleController(CloudDataBase context)
        {
            _context = context;
        }

        #region base     
        #region 获取分页信息
        /// <summary>
        /// 获取分页信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("GetList")]
        [HttpPost]
        public async Task<JsonResponse<DataList<Apple>>> GetList([FromHeader] string Authorization, sApple sPage)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<DataList<Apple>>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            response.Data = new DataList<Apple>();

            new Helper().sPageNew(sPage);

            DateTime dtStart = Convert.ToDateTime(sPage.startDate.ToString("yyyy-MM-dd 00:00:00"));
            DateTime dtEnd = Convert.ToDateTime(sPage.endDate.ToString("yyyy-MM-dd 23:59:59"));
            var listQuery = _context.Apple.Where(t => t.OperatDate >= dtStart && t.OperatDate <= dtEnd);
            if (!string.IsNullOrEmpty(sPage.Name))
            {
                listQuery = listQuery.Where(t => t.Name.Contains(sPage.Name));
            }
            if (!string.IsNullOrEmpty(sPage.IsPayment))
            {
                listQuery = listQuery.Where(t => t.Payment.Contains(sPage.IsPayment));
            }
            if (!string.IsNullOrEmpty(sPage.IsDeliver))
            {
                listQuery = listQuery.Where(t => t.DeliverGoods.Contains(sPage.IsDeliver));
            }
            response.Data.Total = await listQuery.CountAsync().ConfigureAwait(false);
            var list = await listQuery
                   .OrderByDescending(t => t.Id)
                   .Skip((int)sPage.PageIndex * (int)sPage.PageSize)
                   .Take((int)sPage.PageSize)
                   .ToArrayAsync()
                   .ConfigureAwait(false);
            response.Data.Count = list.Length;
            response.Data.List = list;
            response.Msg = "查询成功";
            response.Status = ResponseStatus.Success;

            //------------------------------------------------
            //_context.Apple.OrderByDescending(s => s.RealName);
            //_context.Apple.OrderBy(s => s.CreateDate);
            //------------------------------------------------
            return response;
        }
        #endregion

        #region 苹果订单添加
        /// <summary>
        /// 苹果订单添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Route("AppleAdd")]
        [HttpPost]
        public async Task<JsonResponse> AppleAdd([FromHeader] string Authorization, Apple entity = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }

            //var data = await _context.Apple.FirstOrDefaultAsync(t => t.Id == entity.Id).ConfigureAwait(false);
            //if (data != null)
            //{
            //    response.Msg = "添加失败,该苹果订单已存在";
            //    response.Status = ResponseStatus.MultipleData;
            //    return response;
            //}

            var arr = _context.Apple.Select(t => t.Id).ToArray();
            int maxNum = 0;
            if (arr.Length > 0)
            {
                maxNum = arr.Max();
            }
            entity.Id = maxNum + 1;
            entity.OperatDate = DateTime.Now;
            entity.CreateDate = DateTime.Now;
            entity.ModifyDate = DateTime.Now;
            entity.DeliverGoods = "0";
            _context.Set<Apple>().Add(entity);
            //int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "苹果订单添加成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "添加失败";
                response.Status = ResponseStatus.ParameterError;
            }
            string et = response.Msg + "-实体内容:" + new Helper().ObjectToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));


            return response;
        }
        #endregion

        #region 苹果订单编辑
        /// <summary>
        /// 苹果订单编辑 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AppleUpdate")]
        public async Task<JsonResponse> AppleUpdate([FromHeader] string Authorization, Apple entity = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            var dataCount = _context.Set<Apple>().Where(c => c.Id == entity.Id).Count();

            //var data = await _context.Apple.FirstOrDefaultAsync(t => t.Id == entity.Id).ConfigureAwait(false);
            if (dataCount == 0)
            {
                response.Msg = "修改失败,数据不存在";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            entity.ModifyDate = DateTime.Now;
            entity.OperatDate = DateTime.Now;
            _context.Set<Apple>().Update(entity);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "苹果订单修改成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "修改失败";
                response.Status = ResponseStatus.ProcessFail;
            }
            string et = response.Msg + "-修改数据:" + new Helper().objToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));

            return response;
        }

        #endregion

        #region 苹果订单删除
        /// <summary>
        /// 苹果订单删除 
        /// </summary>
        /// <param name="aaa"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("AppleDel")]
        public async Task<JsonResponse> AppleDel([FromHeader] string Authorization, string ids = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);

            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (ids.Length == 0)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
            }

            int[] arr = ids.TrimEnd(',').Split(',').Select(t => Convert.ToInt32(t)).ToArray();

            var Apples = _context.Apple.Where(c => arr.Contains(c.Id));

            var dataCount = Apples.Count();
            if (dataCount == 0)
            {
                response.Msg = "数据不存在,不允许删除";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            string delArr = new Helper().objToJson(Apples);

            _context.Apple.RemoveRange(Apples);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "苹果订单删除成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "苹果订单删除失败";
                response.Status = ResponseStatus.ParameterError;
            }
            delArr = response.Msg + "-删除集合:" + delArr;
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, delArr), RouteData.Values.Values.Join(","));

            return response;
        }
        #endregion

        #region 苹果订单确认支付
        /// <summary>
        /// 苹果订单确认支付 
        /// </summary>
        /// <param name="aaa"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("ApplePayment")]
        public async Task<JsonResponse> ApplePayment([FromHeader] string Authorization, string ids = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);

            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (ids.Length == 0)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
            }

            int[] arr = ids.TrimEnd(',').Split(',').Select(t => Convert.ToInt32(t)).ToArray();

            var Apples = _context.Apple.Where(c => arr.Contains(c.Id));

            var dataCount = Apples.Count();
            if (dataCount == 0)
            {
                response.Msg = "数据不存在,不允许付款";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            string delArr = new Helper().objToJson(Apples);

            var d = Apples.ToArray();
            for (int i = 0; i < d.Count(); i++)
            {
                d[i].Payment = "1";
            }
            _context.Apple.UpdateRange(d);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "苹果订单付款成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "苹果订单付款失败";
                response.Status = ResponseStatus.ParameterError;
            }
            delArr = response.Msg + "-付款集合:" + delArr;
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, delArr), RouteData.Values.Values.Join(","));

            return response;
        }
        #endregion  

        #region 苹果订单确认发货
        /// <summary>
        /// 苹果订单确认发货
        /// </summary>
        /// <param name="aaa"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("AppleDeliver")]
        public async Task<JsonResponse> AppleDeliver([FromHeader] string Authorization, string ids = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);

            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (ids.Length == 0)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
            }

            int[] arr = ids.TrimEnd(',').Split(',').Select(t => Convert.ToInt32(t)).ToArray();

            var Apples = _context.Apple.Where(c => arr.Contains(c.Id));

            var dataCount = Apples.Count();
            if (dataCount == 0)
            {
                response.Msg = "数据不存在,不允许删除";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            string delArr = new Helper().objToJson(Apples);

            var d = Apples.ToArray();
            for (int i = 0; i < d.Count(); i++)
            {
                d[i].DeliverGoods = "1";
            }
            _context.Apple.UpdateRange(d);

            int num = _context.SaveChanges();



            if (num > 0)
            {
                response.Msg = "苹果订单发货成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "苹果订单发货失败";
                response.Status = ResponseStatus.ParameterError;
            }
            delArr = response.Msg + "-删除集合:" + delArr;
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, delArr), RouteData.Values.Values.Join(","));

            return response;
        }
        #endregion  
        #endregion
    }
}
